package com.lwq.code;

import io.netty.channel.Channel;
import io.netty.handler.codec.http.HttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Description:
 * Author: LiuWenQing
 * Datetime: 2021/6/16
 */
public class WebSocketUserUtil {

    public static boolean isShowLog = true;
    private static Map<String, Channel> channelMap = new ConcurrentHashMap<>(10000);
    private static Logger logger = LoggerFactory.getLogger(WebSocketUserUtil.class);
    public static String[] accounts = new String[]{"liuwenqing","zhangsan","lisi","wangwu","zhaoliu","jia","yi","bing","ding","abc"};

    public static Map<String, Channel> getChannelMap() {
        return channelMap;
    }

    public static void removeChannelByKey(String key) {
        channelMap.remove(key);
    }

    public static void removeChannelByChannel(Channel channel) {
        Set<Map.Entry<String, Channel>> entries = channelMap.entrySet();
        Iterator<Map.Entry<String, Channel>> iterator = entries.iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Channel> next = iterator.next();
            Channel value = next.getValue();
            if (value.id().equals(channel.id())) {
                iterator.remove();
            }
        }
    }


    public static String getUserName(Channel channel) {
        Set<Map.Entry<String, Channel>> entries = channelMap.entrySet();
        for (Map.Entry<String, Channel> map : entries){
            if(map.getValue().id().equals(channel.id())){
                return map.getKey().split(",")[0];
            }
        }
        return "";
    }

    public static String getUserId(HttpRequest msg) {
        String uri = msg.getUri();
        int index = uri.lastIndexOf("/");
        if (index < 0) {
            return null;
        }
        return uri.substring(index + 1);
    }

//    public static void sendMessageNotify(String userId ,String msg, String notifyType, String channelId){
//        SendBody sendBody = new SendBody();
//        sendBody.setMessage(msg);
//        sendBody.setTypeCode(notifyType);
//        sendBody.setType(SendBody.GROUP_BROADCAST);
//        List<String> list = new ArrayList<>();
//        for(String key : channelMap.keySet()){
//            if(!list.contains(key.split(",")[0])){
//                list.add(key.split(",")[0]);
//            }
//        }
//        Set set = new HashSet(list);
//        sendBody.setOnlineCount(set.size());
//        broadCast(userId, channelId,sendBody);
//    }

//    public static void sendMessageReply(String userId,String messageId, String parentId, String message){
//        SendBody sendBody = new SendBody();
//        sendBody.setId(messageId);
//        sendBody.setFrom(userId);
//        sendBody.setMessage(message);
//        sendBody.setCreateDate(DateUtil.getNowDateStr());
//        sendBody.setType(SendBody.GROUP_BROADCAST);
//        sendBody.setTypeCode(SendBody.REPLY);
//        sendBody.setParentId(parentId);
//        broadCast(sendBody);
//    }

//    public static void sendMessageReaded(String messageId, Integer unReadedCount){
//        SendBody sendBody = new SendBody();
//        sendBody.setId(messageId);
//        sendBody.setType(SendBody.GROUP_BROADCAST);
//        sendBody.setUnReadedCount(unReadedCount);
//        sendBody.setTypeCode(SendBody.READED);
//        broadCast(sendBody);
//    }
//
//    public static void sendMessageRecall(String messageId, String userId){
//        SendBody sendBody = new SendBody();
//        sendBody.setId(messageId);
//        sendBody.setFrom(userId);
//        sendBody.setType(SendBody.GROUP_BROADCAST);
//        sendBody.setTypeCode(SendBody.RECALL);
//        broadCast(sendBody);
//    }

    /**
     * 群发消息
     */
//    public static void sendMessageToAll(String userId, String msg, String messageId){
//        SendBody sendBody = new SendBody();
//        sendBody.setFrom(userId);
//        sendBody.setMessage(msg);
//        sendBody.setType(SendBody.GROUP_BROADCAST);
//        sendBody.setId(messageId);
//        sendBody.setTypeCode(SendBody.SEND);
//        sendBody.setUnReadedCount(ListUtil.removeFromList(userId,Arrays.asList(accounts)).size());
//        sendBody.setCreateDate(DateUtil.getNowDateStr());
//        broadCast(sendBody);
//    }

    /**
     * 单聊
     * @param sendUserId
     * @param fromUserId
     * @param msg
     * @param type
     */
//    public static void sendMessageToUser(String sendUserId, String fromUserId,String msg,String type) {
//        Channel channel = channelMap.get(sendUserId);
//        if (channel != null) {
//            if (isShowLog) {
//                logger.info("发送消息：id = " + sendUserId + "channel id = " + channel.id() + "isWritable = " + channel.isWritable());
//            }
//            SendBody sendBody = new SendBody();
//            sendBody.setFrom(sendUserId);
//            sendBody.setFrom(fromUserId);
//            sendBody.setMessage(msg);
//            sendBody.setType(type);
//            if (channel.isWritable()) {
//                channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(sendBody)));
//            } else {
//                try {
//                    channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(sendBody))).sync();
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//    }
}
